package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import com.tensquare.util.IdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务层代码
 */
@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 吐槽点赞
     * @param id
     */
    public void thumbup(String id) {

        // db.spit.update({},{})
        //更新谁
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));

        //更新的值
        Update update = new Update();
        update.inc("thumbup",1);

        //执行更新
        mongoTemplate.updateFirst(query,update,"spit");
    }
/*    public void thumbup(String id) {
        Spit spit = spitDao.findById(id).get();
        spit.setThumbup(spit.getThumbup()==null? 1 : spit.getThumbup()+1);
        spitDao.save(spit);
    }*/

    /**
     *
     * @param parentid
     * @param page
     * @param size
     * @return
     */
    public Page<Spit> comment(String parentid, int page, int size) {
        return spitDao.findByParentid(parentid, PageRequest.of(page-1,size));
    }

    //查询所有
    public List<Spit> findAll(){
        return spitDao.findByParentidIsNull();
    }
    //查询一个
    public Spit findById(String id){
        return spitDao.findById(id).get();
    }
    //新增
    public void add(Spit spit){

        //添加的是一个评论：parentid不为空  ； 为空就是吐槽
        spit.setId(idWorker.nextId()+"");
        spitDao.save(spit);

        //更新回复数： 只有当前操作是添加评论的时候，才会让回复数加一
        //当前操作就是添加评论
        if(StringUtils.isNotBlank(spit.getParentid())){
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));

            Update update = new Update();
            update.inc("comment",1);
            //对评论数加一
            mongoTemplate.updateFirst(query,update,"spit");
        }
    }
    //修改
    public void update(Spit spit){
        spitDao.save(spit);
    }
    //删除
    public void deleteById(String id){
        spitDao.deleteById(id);
    }


}
